package core.algorithm.operator.Selection;

import core.problem.Individual;
import core.problem.Population;
import core.tools.MyMath.RandomGenerator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author 郝国生 HAO Guo-Sheng
 */
public class StochasticTournamentModel extends AbstractSelection {

    @Override
    public List<Individual> getSelectionResult(Population population) {
        if (continueSelection(population)) {
            List<Individual> result = new LinkedList<>();
            int k, j;
            int size = population.getIndividuals().size();
            for (Object individual : population.getIndividuals()) {
                k = RandomGenerator.getRandom(0, size);
                j = RandomGenerator.getRandom(0, size);
                Individual temk = (Individual)population.getIndividuals().get(k),
                        temj = (Individual)population.getIndividuals().get(j);
                try {
                    result.add((Individual) (temk.compareTo(temj) >= 0 ? temk.clone() : temj.clone()));
                } catch (CloneNotSupportedException ex) {
                    Logger.getLogger(StochasticTournamentModel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return result;
        } else {
            return new LinkedList<>(population.getIndividuals());
        }
    }

}
